<?php
/**
 * Yotaku Shop - yshop
 * @author Creatint<creatint@163.com>
 * @copyright www.yotaku.cn 2016
 */
namespace Home\Model;
use Think\Model;
use Think\Page;
class GoodsModel extends Model{
    protected $error   =   '';
    protected $show   =   '';

    /**
     * @describe 根据条件获取商品
     * @author Creatint
     * @param null $params
     * @param bool $page
     * @return mixed
     */
    public function getGoods($params=null,$page=false){

        //初始化查询条件
        $map        =   array();
        //商品标题
        if(!empty($params['title'])){
            $map['title']   =   array('like', '%'.(string)$params['title'].'%');
        }
        //分类ID
        if(!empty($params['category'])){
            $map['category_id']   =   $params['category'];
        }
        //商品价格
        if(!empty($params['price'])){
            $arr_tmp    =   explode(',',$params['price']);
            $map['price']   =   array('between',$arr_tmp);
            unset($arr_tmp);
        }
        //商品库存
        if(!empty($params['stock'])){
            $arr_tmp    =   explode(',',$params['stock']);
            $map['stock']   =   array('between',$arr_tmp);
            unset($arr_tmp);
        }
        if(!empty($params['status'])){
            $map['status']  =   (int)$params['status'];
        }
        if(!empty($params['position'])){
            $map['_string']  =   "position & {$params['position']} = {$params['position']}";
        }

        //商品分类
        if(!empty($params['category_id'])){
            $map['category_id']  =   (int)$params['category_id'];
        }

        //销量排序 降序
        if(!empty($params['sales'])){
            $order = "sales {$params['sales']}";
        }
        //创建时间排序
        if(!empty($params['created_time'])){
            $order = "created_at desc";
        }
        //价格排序
        if('desc' == $params['price_order']){
            $order = "price desc";
        }elseif('asc' == $params['price_order']){
            $order = "price asc";
        }

        if($map['_string'])
            $map['_string'] .= " AND (pubstart=0 AND pubend=0) OR (pubstart<time() AND pubend >time())";
        else
            $map['_string'] = " (pubstart=0 AND pubend=0) OR (pubstart<".time()." AND pubend >".time().")";
        trace($map,'map');



        //是否分页
        if($page){
            $result =   $this->where($map)->page($_GET['p'].',25')->order($order)->select();
            if($result){
                $count  =   $this->where($map)->count();
                $Page   =   new Page($count,25);
                $Page->setConfig('wrap',array('<li>','</li>','<li class="active">'));
                $Page->setConfig('prev','«');
                $Page->setConfig('next','»');
                $this->show   =   $Page->show();
            }
        }else{
            $result =   $this->where($map)->order($order)->select();
        }

//        dump($order);
//        dump($this->getLastSql());
        return $result;
    }

    public function getDetail($id,$field=true){
        $info   =   $this->field($field)->find($id);
        //trace($info,'model_info');
        if(!is_array($info)){
            $this->error    =   '商品不存在';
            return false;
        }
        //增加浏览次数
        $this->where("id={$id}")->setInc('view');
        return $info;
    }
    public function updateGoods($data=null){
        $data   =   $this->create($data);
        if(empty($data)){
            $this->error    =   '数据为空';
            return false;
        }
        trace($data,'data');

        /* 添加或新增基础内容 */
        if(empty($data['id'])){ //新增数据
            $id = $this->add(); //添加基础内容
            if(!$id){
                $this->error = '新增商品内容出错！';
                return false;
            }
        } else { //更新数据
            $status = $this->save(); //更新基础内容
            if(false === $status){
                $this->error = '更新商品内容出错！';
                return false;
            }
        }
        //商品添加或更新完成
        return $data;
    }


    /**
     * 获取推荐位数据列表
     * @param  number  $pos      推荐位 1-列表推荐，2-频道页推荐，4-首页推荐
     * @param  number  $category 分类ID
     * @param  number  $limit    列表行数
     * @param  boolean $filed    查询字段
     * @return array             数据列表
     */
    public function position($pos, $category = null, $limit = null, $field = "id,category_id,status,position,title,price,multimage"){

        $map = $this->listMap($category, 1, $pos);
        trace($pos,'pos');

        /* 设置列表数量 */
        is_numeric($limit) && $this->limit($limit);

        /* 读取数据 */
        $result =   $this->where($map)->order("update_at desc")->field($field)->select();
//        trace($this->getLastSql());
//        trace($result,'position');

        return $result;
    }

    /**
     * 获取推荐位数据列表
     * @param  number  $pos      推荐位 1-列表推荐，2-频道页推荐，4-首页推荐
     * @param  number  $category 分类ID
     * @param  number  $limit    列表行数
     * @param  boolean $filed    查询字段
     * @return array             数据列表
     */
    public function activity($act, $category = null, $limit = null, $field = "id,category_id,status,position,title,price,multimage"){

        $map = $this->listMap($category, $status = 1, $pos = null,$act);
        trace($act,'act');

        /* 设置列表数量 */
        //is_numeric($limit) && $this->limit($limit);

        /* 读取数据 */
        $result =   $this->where($map)->order("update_at desc")->field($field)->select();
        $result = hook('activity_show',array('goodss'=>$result, 'limit'=>$limit));


//        trace($this->getLastSql());
//        trace($result,'position');

        return $result;
    }


    /**
     * 获取推荐位数据列表
     * @param  number  $pos      推荐位 1-列表推荐，2-频道页推荐，4-首页推荐
     * @param  number  $category 分类ID
     * @param  number  $limit    列表行数
     * @param  boolean $filed    查询字段
     * @return array             数据列表
     */
    public function activity_info($goods_id, $field = "id,category_id,status,position,title,price,multimage"){

        $map['id'] = $goods_id;

        /* 设置列表数量 */
        //is_numeric($limit) && $this->limit($limit);

        /* 读取数据 */
        $result =   $this->where($map)->order("update_at desc")->field($field)->select();
        $result = hook('activity_show',array('goodss'=>$result));


//        trace($this->getLastSql());
//        trace($result,'position');

        return $result;
    }



    /**
     * 设置where查询条件
     * @param  number  $category 分类ID
     * @param  number  $pos      推荐位
     * @param  integer $status   状态
     * @return array             查询条件
     */
    private function listMap($category, $status = 1, $pos = null, $act = null){
        /* 设置状态 */
        $map = array('status' => $status);

        /* 设置分类 */
        if(!is_null($category)){
            if(is_numeric($category)){
                $map['category_id'] = $category;
            } else {
                $map['category_id'] = array('in', str2arr($category));
            }
        }else{
            $map['category_id'] = array('egt',0);//category_id>0
        }

        //时间限制
        //$map['created_at'] = array('lt', NOW_TIME);

        /* 设置推荐位 */
        if(is_numeric($pos)){
            $map[] = "position & {$pos} = {$pos}";
        }
        /* 设置活动位 */
        if(is_numeric($act)){
            $map[] = "activity & {$act} = {$act}";
        }

        //$map    =   array_filter($map);
        return $map;
    }

    //获取错误
    public function getError(){
        return $this->error;
    }

    //分页html元素
    public function getShow(){
        return $this->show;
    }
}
